package com.mxchip.livestar.utils;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * =======================================================
 * 版权：Copyright LiYing 2015-2016. All rights reserved.
 * 作者：liying - liruoer2008@yeah.net
 * 日期：2016/12/19 19:43
 * 版本：1.0
 * 描述：IP地址工具类
 * 备注：
 * =======================================================
 */
public class IPUtils {
private Context mContext;

    public void setmContext(Context mContext) {
        this.mContext = mContext;
    }

    /**
     * 获取本机IPv4地址
     *
     * @param context
     * @return 本机IPv4地址；null：无网络连接
     */
    public static String getIpAddress(Context context) {
        // 获取WiFi服务
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // 判断WiFi是否开启
        if (wifiManager.isWifiEnabled()) {
            // 已经开启了WiFi
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            String ip = intToIp(ipAddress);
            return ip;
        } else {
            // 未开启WiFi
            return getIpAddress();
        }
    }

    private static String intToIp(int ipAddress) {
        return (ipAddress & 0xFF) + "." +
                ((ipAddress >> 8) & 0xFF) + "." +
                ((ipAddress >> 16) & 0xFF) + "." +
                (ipAddress >> 24 & 0xFF);
    }

    /**
     * 获取本机IPv4地址
     *
     * @return 本机IPv4地址；null：无网络连接
     */
    private static String getIpAddress() {
        try {
            NetworkInterface networkInterface;
            InetAddress inetAddress;
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                networkInterface = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
            return null;
        } catch (SocketException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static String getNetMaskIps(Context context) {


        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo di = wm.getDhcpInfo();
        long netmaskIpL = di.netmask;
        String netmaskIpS = long2ip(netmaskIpL);
        return netmaskIpS;
    }

    public static String getAll(Context context) {
        WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcpInfo = wm.getDhcpInfo();
        StringBuilder sb = new StringBuilder();
        WifiInfo wifiInfo = wm.getConnectionInfo();
        sb.append("网络信息：");
        sb.append("\nipAddress：" + intToIp(dhcpInfo.ipAddress));
        sb.append("\nnetmask：" + intToIp(dhcpInfo.netmask));
        sb.append("\ngateway：" + intToIp(dhcpInfo.gateway));
        sb.append("\nserverAddress：" + intToIp(dhcpInfo.serverAddress));
        sb.append("\ndns1：" + intToIp(dhcpInfo.dns1));
        sb.append("\ndns2：" + intToIp(dhcpInfo.dns2));
        sb.append("\n");
        System.out.println(intToIp(dhcpInfo.ipAddress));
        System.out.println(intToIp(dhcpInfo.netmask));
        System.out.println(intToIp(dhcpInfo.gateway));
        System.out.println(intToIp(dhcpInfo.serverAddress));
        System.out.println(intToIp(dhcpInfo.dns1));
        System.out.println(intToIp(dhcpInfo.dns2));
        System.out.println(dhcpInfo.leaseDuration);

        sb.append("Wifi信息：");
        sb.append("\nIpAddress：" + intToIp(wifiInfo.getIpAddress()));
        sb.append("\nMacAddress：" + wifiInfo.getMacAddress());
        return sb.toString();

    }

    public static String long2ip(long ip) {
        StringBuffer sb = new StringBuffer();
        sb.append(String.valueOf((int) (ip & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 8) & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 16) & 0xff)));
        sb.append('.');
        sb.append(String.valueOf((int) ((ip >> 24) & 0xff)));
        return sb.toString();
    }


    public static String[] readDnsServers(Context context) {
        String[] dnsServers = readDnsServersFromConnectionManager(context);
        if (dnsServers == null || dnsServers.length == 0) {
            dnsServers = readDnsServersFromSystemProperties();
            if (dnsServers == null || dnsServers.length == 0) {
                dnsServers = readDnsServersFromCommand();
            }
        }
        return dnsServers == null ? new String[0] : dnsServers;
    }

    public static String[] readDnsServersFromConnectionManager(Context context) {
        LinkedList<String> dnsServers = new LinkedList<>();
        if (Build.VERSION.SDK_INT >= 21 && context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
            if (connectivityManager != null) {
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                for (Network network : connectivityManager.getAllNetworks()) {
                    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                    if (networkInfo.getType() == activeNetworkInfo.getType()) {
                        LinkProperties lp = connectivityManager.getLinkProperties(network);
                        for (InetAddress addr : lp.getDnsServers()) {
                            dnsServers.add(addr.getHostAddress());
                        }
                    }
                }
            }
        }
        return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
    }

    public static String[] readDnsServersFromCommand() {
        LinkedList<String> dnsServers = new LinkedList<>();
        try {
            Process process = Runtime.getRuntime().exec("getprop");
            InputStream inputStream = process.getInputStream();
            LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inputStream));
            String line = null;
            while ((line = lnr.readLine()) != null) {
                int split = line.indexOf("]: [");
                if (split == -1) continue;
                String property = line.substring(1, split);
                String value = line.substring(split + 4, line.length() - 1);
                if (property.endsWith(".dns")
                        || property.endsWith(".dns1")
                        || property.endsWith(".dns2")
                        || property.endsWith(".dns3")
                        || property.endsWith(".dns4")) {
                    InetAddress ip = InetAddress.getByName(value);
                    if (ip == null) continue;
                    value = ip.getHostAddress();
                    if (value == null) continue;
                    if (value.length() == 0) continue;
                    dnsServers.add(value);
                }
            }
        } catch (IOException e) {
        }
        return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
    }

    //反射 SystemProperties
    private static final String[] DNS_SERVER_PROPERTIES = new String[]{"net.dns1",
            "net.dns2", "net.dns3", "net.dns4"};

    public static String[] readDnsServersFromSystemProperties() {
        SystemProperties.init();
        LinkedList<String> dnsServers = new LinkedList<>();
        for (String property : DNS_SERVER_PROPERTIES) {
            String server = SystemProperties.get(property, "");
            if (server != null && !server.isEmpty()) {
                try {
                    InetAddress ip = InetAddress.getByName(server);
                    if (ip == null) continue;
                    server = ip.getHostAddress();
                    if (server == null || server.isEmpty()) {
                        continue;
                    }
                } catch (Throwable throwable) {
                    continue;
                }
                dnsServers.add(server);
            }
        }
        return dnsServers.toArray(new String[dnsServers.size()]);
    }

    public static String[] readDnsServersFromWifiManager(Context context) {
        LinkedList<String> dnsServers = new LinkedList<>();
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager == null || !wifiManager.isWifiEnabled()) {
                return new String[0];
            }
            DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
            if (dhcpInfo != null) {
                if (dhcpInfo.dns1 != 0) {
                    dnsServers.add(intToIp(dhcpInfo.dns1));
                }
                if (dhcpInfo.dns2 != 0) {
                    dnsServers.add(intToIp(dhcpInfo.dns2));
                }
            }
        } catch (Exception e) {
        }
        return dnsServers.isEmpty() ? new String[0] : dnsServers.toArray(new String[dnsServers.size()]);
    }

    public static class SystemProperties {
        private static boolean isReflectInited = false;

        public static void init() {
            if (!isReflectInited) {
                isReflectInited = true;
                try {
                    Class<?> cls = Class.forName("android.os.SystemProperties");
                    setPropertyMethod = cls.getDeclaredMethod("set", new Class<?>[]{String.class, String.class});
                    setPropertyMethod.setAccessible(true);
                    getPropertyMethod = cls.getDeclaredMethod("get", new Class<?>[]{String.class, String.class});
                    getPropertyMethod.setAccessible(true);
                } catch (Throwable throwable) {
                }
            }
        }

        private static Method getPropertyMethod = null;

        public static String get(String property, String defaultValue) {
            String propertyValue = defaultValue;
            if (getPropertyMethod != null) {
                try {
                    propertyValue = (String) getPropertyMethod.invoke(null, property, defaultValue);
                } catch (Throwable throwable) {
                }
            }
            return propertyValue;
        }

        private static Method setPropertyMethod = null;

        public static void set(String property, String value) {
            if (setPropertyMethod != null) {
                try {
                    setPropertyMethod.invoke(null, property, value);
                } catch (Throwable throwable) {
                }
            }
        }
    }

    private static InetAddress inetAddress;
    private static Object ipConfigurationInstance;
    public static void setIP(Context context, String mode) {
        try {
            // 获取ETHERNET_SERVICE参数
            String ETHERNET_SERVICE = (String) Context.class.getField(
                    "ETHERNET_SERVICE").get(null);
            @SuppressLint("PrivateApi") Class<?> ethernetManagerClass = Class
                    .forName("android.net.EthernetManager");
            @SuppressLint("PrivateApi") Class<?> ipConfigurationClass = Class
                    .forName("android.net.IpConfiguration");
            // 获取ethernetManager服务对象
            Object ethernetManager = context.getSystemService(ETHERNET_SERVICE);
            Object getConfiguration = ethernetManagerClass.getDeclaredMethod(
                    "getConfiguration").invoke(ethernetManager);
            // 获取在EthernetManager中的抽象类mService成员变量
            Field mService = ethernetManagerClass.getDeclaredField("mService");
            // 修改private权限
            mService.setAccessible(true);
            // 获取抽象类的实例化对象
            Object mServiceObject = mService.get(ethernetManager);
            @SuppressLint("PrivateApi") Class<?> iEthernetManagerClass = Class
                    .forName("android.net.IEthernetManager");
            Method[] methods = iEthernetManagerClass.getDeclaredMethods();
            for (Method ms : methods) {
                if (ms.getName().equals("setEthernetEnabled")) {
                    ms.invoke(mServiceObject, true);
                }
            }
            @SuppressLint("PrivateApi") Class<?> staticIpConfig = Class
                    .forName("android.net.StaticIpConfiguration");
            Constructor<?> staticIpConfigConstructor = staticIpConfig
                    .getDeclaredConstructor(staticIpConfig);
            Object staticIpConfigInstance = staticIpConfig.newInstance();
            // 获取LinkAddress里面只有一个String类型的构造方法
            Class<?> linkAddressClass = Class
                    .forName("android.net.LinkAddress");
            Constructor<?> linkAddressConstructor = linkAddressClass
                    .getDeclaredConstructor(String.class);
            // 实例化带String类型的构造方法
            // 192.168.88.22/24--子网掩码长度,24相当于255.255.255.0, 此处必须按照这个样式来设置才行
            Object linkAddress = (Object) linkAddressConstructor
                    .newInstance("192.168.88.22/24");
            Class<?> inetAddressClass = Class.forName("java.net.InetAddress");
            // 默认网关参数
            int[] bytes = new int[]{(byte) 192, (byte) 168, 88, 254};
            Constructor<?>[] inetAddressConstructors = inetAddressClass
                    .getDeclaredConstructors();
            for (Constructor inetc : inetAddressConstructors) {
                // 获取有三种参数类型的构造方法
                if (inetc.getParameterTypes().length == 3) {
                    // 修改权限
                    inetc.setAccessible(true);
                    WifiManager wm = (WifiManager)  context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    int ipAddressInt = wm.getConnectionInfo().getIpAddress();
                    // hostName主机名
                    String hostName = String.format(Locale.getDefault(),
                            "%d.%d.%d.%d", (ipAddressInt & 0xff),
                            (ipAddressInt >> 8 & 0xff),
                            (ipAddressInt >> 16 & 0xff),
                            (ipAddressInt >> 24 & 0xff));
                    inetAddress = (InetAddress) inetc.newInstance(2, bytes,
                            hostName);
                }
            }
            // 获取staticIpConfig中所有的成员变量
            Field[] declaredFields = staticIpConfigInstance.getClass()
                    .getDeclaredFields();
            InetAddress address = InetAddress.getByName("192.168.88.254");
            Class<?> threadClazz = Class.forName("android.net.NetworkUtils");
            Method method = threadClazz.getMethod("numericToInetAddress",
                    String.class);
            Object inetAddressObject1 = method.invoke(null, "8.8.8.8");
            Object inetAddressObject2 = method.invoke(null, "8.8.4.4");
            ArrayList<Object> inetAddresses = new ArrayList<Object>();
            inetAddresses.add(inetAddressObject1);
            inetAddresses.add(inetAddressObject2);
            for (Field f : declaredFields) {
                // 设置成员变量的值
                if (f.getName().equals("ipAddress")) {
                    // 设置IP地址和子网掩码
                    f.set(staticIpConfigInstance, linkAddress);
                } else if (f.getName().equals("gateway")) {
                    // 设置默认网关
                    f.set(staticIpConfigInstance, address);
                } else if (f.getName().equals("domains")) {
                    f.set(staticIpConfigInstance, " ");
                } else if (f.getName().equals("dnsServers")) {
                    // 设置DNS，必须要设置才能成功
                    f.setAccessible(true);
                    f.set(staticIpConfigInstance, inetAddresses);
                }
            }
            Object staticInstance = staticIpConfigConstructor
                    .newInstance(staticIpConfigInstance);
            // 存放ipASSignment枚举类参数的集合
            HashMap ipAssignmentMap = new HashMap();
            // 存放proxySettings枚举类参数的集合
            HashMap proxySettingsMap = new HashMap();
            Class<?>[] enumClass = ipConfigurationClass.getDeclaredClasses();
            for (Class enumC : enumClass) {
                // 获取枚举数组
                Object[] enumConstants = enumC.getEnumConstants();
                if (enumC.getSimpleName().equals("ProxySettings")) {
                    for (Object enu : enumConstants) {
                        // 设置代理设置集合 STATIC DHCP UNASSIGNED PAC
                        proxySettingsMap.put(enu.toString(), enu);
                    }
                } else if (enumC.getSimpleName().equals("IpAssignment")) {
                    for (Object enu : enumConstants) {
                        // 设置以太网连接模式设置集合 STATIC DHCP UNASSIGNED
                        ipAssignmentMap.put(enu.toString(), enu);
                    }
                }
            }
            // 获取ipConfiguration类的构造方法
            Constructor<?>[] ipConfigConstructors = ipConfigurationClass
                    .getDeclaredConstructors();
            Class<?> proxyInfo = Class.forName("android.net.ProxyInfo");
            Method methodProxy = proxyInfo.getMethod("buildDirectProxy",
                    String.class, int.class);
            // Object inetAddressObject1 = method.invoke(null, "8.8.8.8");


            for (Constructor constru : ipConfigConstructors) {
                // 获取ipConfiguration类的4个参数的构造方法
                if (constru.getParameterTypes().length == 4) {// 设置以上四种类型
                    // 初始化ipConfiguration对象,设置参数
                    ipConfigurationInstance = constru.newInstance(
                            ipAssignmentMap.get(mode),
                            proxySettingsMap.get("NONE"), staticInstance,
                            methodProxy.invoke(null, null, 0));
                }
            }
            // 获取ipConfiguration类中带有StaticIpConfiguration参数类型的名叫setStaticIpConfiguration的方法
            Method setStaticIpConfiguration = ipConfigurationClass
                    .getDeclaredMethod("setStaticIpConfiguration",
                            staticIpConfig);
            // 修改private方法权限
            setStaticIpConfiguration.setAccessible(true);
            // 在ipConfiguration对象中使用setStaticIpConfiguration方法,并传入参数
            setStaticIpConfiguration.invoke(ipConfigurationInstance,
                    staticInstance);
            Object ethernetManagerInstance = ethernetManagerClass
                    .getDeclaredConstructor(Context.class,
                            iEthernetManagerClass).newInstance(context,
                            mServiceObject);
            ethernetManagerClass.getDeclaredMethod("setConfiguration",
                    ipConfigurationClass).invoke(ethernetManagerInstance,
                    ipConfigurationInstance);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置静态ip地址的方法
     */

    public static boolean setIpWithTfiStaticIp(Context mContext,boolean dhcp, String ip, int prefix, String dns1, String gateway,String netMask) {
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
        boolean flag=false;
        if (!wifiManager.isWifiEnabled()) {
            // wifi is disabled
            return flag;
        }
        // get the current wifi configuration
        WifiConfiguration wifiConfig = null;

        WifiInfo connectionInfo = wifiManager.getConnectionInfo();
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        if (configuredNetworks != null) {
            for (WifiConfiguration conf : configuredNetworks) {
                if (conf.networkId == connectionInfo.getNetworkId()) {
                    wifiConfig = conf;
                    break;
                }
            }
        }

        if (wifiConfig == null) {
            // wifi is not connected
            return flag;
        }
        if (Build.VERSION.SDK_INT < 11) { // 如果是android2.x版本的话
            ContentResolver ctRes = mContext.getContentResolver();
            Settings.System.putInt(ctRes,
                    Settings.System.WIFI_USE_STATIC_IP, 1);
            Settings.System.putString(ctRes,
                    Settings.System.WIFI_STATIC_IP, "192.168.0.202");
            Settings.System.putString( mContext.getContentResolver(), Settings.System.WIFI_USE_STATIC_IP, "1");
            Settings.System.putString( mContext.getContentResolver(), Settings.System.WIFI_STATIC_DNS1, dns1);
            //默认网关
            Settings.System.putString( mContext.getContentResolver(), Settings.System.WIFI_STATIC_GATEWAY, gateway);
            //子网掩码
            Settings.System.putString( mContext.getContentResolver(), Settings.System.WIFI_STATIC_NETMASK, netMask);
            //ipv4地址
            Settings.System.putString( mContext.getContentResolver(), Settings.System.WIFI_STATIC_IP, ip);
            flag=true;
            return flag;
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { // 如果是android3.x版本及以上的话

            try {
                setIpAssignment("STATIC", wifiConfig);
                setIpAddress(InetAddress.getByName(ip), prefix, wifiConfig);
                setGateway(InetAddress.getByName(gateway), wifiConfig);
                setDNS(InetAddress.getByName(dns1), wifiConfig);
                int netId = wifiManager.updateNetwork(wifiConfig);
                boolean result =  netId!= -1; //apply the setting
                if(result){
                    boolean isDisconnected =  wifiManager.disconnect();
                    boolean configSaved = wifiManager.saveConfiguration(); //Save it
                    boolean isEnabled = wifiManager.enableNetwork(wifiConfig.networkId, true);
                    // reconnect with the new static IP
                    boolean isReconnected = wifiManager.reconnect();
                }
             /*   wifiManager.updateNetwork(wifiConfig); // apply the setting
                wifiManager.saveConfiguration(); //Save it*/
                System.out.println("静态ip设置成功！");
                flag=true;
                return flag;
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("静态ip设置失败！");
                flag=false;
                return flag;
            }
        } else{//如果是android5.x版本及以上的话
            try {
                Class<?> ipAssignment = wifiConfig.getClass().getMethod("getIpAssignment").invoke(wifiConfig).getClass();
                Object staticConf = wifiConfig.getClass().getMethod("getStaticIpConfiguration").invoke(wifiConfig);

                Log.e("wifiConfig.getClass()",wifiConfig.getClass().toString());

                if (dhcp) {
                    wifiConfig.getClass().getMethod("setIpAssignment", ipAssignment).invoke(wifiConfig, Enum.valueOf((Class<Enum>) ipAssignment, "DHCP"));
                    if (staticConf != null) {
                        staticConf.getClass().getMethod("clear").invoke(staticConf);
                        Log.e("自动分配模式","staticConf!=null");
                    }else{
                        Log.e("自动分配模式","staticConf==null");
                    }
                } else {
                    wifiConfig.getClass().getMethod("setIpAssignment", ipAssignment).invoke(wifiConfig, Enum.valueOf((Class<Enum>) ipAssignment, "STATIC"));
                    if (staticConf == null) {
                        Log.e("静态IP模式","staticConf==null");
                        Class<?> staticConfigClass = Class.forName("android.net.StaticIpConfiguration");
                        staticConf = staticConfigClass.newInstance();
                        if (staticConf == null) {
                            Log.e("静态IP模式","staticConf还是==null");
                        }


                    }else{
                        Log.e("静态IP模式","staticConf！=null");

                    }
                    // STATIC IP AND MASK PREFIX
                    Constructor<?> laConstructor = LinkAddress.class.getConstructor(InetAddress.class, int.class);
                    LinkAddress linkAddress = (LinkAddress) laConstructor.newInstance(
                            InetAddress.getByName(ip),
                            prefix);
                    staticConf.getClass().getField("ipAddress").set(staticConf, linkAddress);
                    // GATEWAY
                    staticConf.getClass().getField("gateway").set(staticConf, InetAddress.getByName(gateway));
                    // DNS
                    List<InetAddress> dnsServers = (List<InetAddress>) staticConf.getClass().getField("dnsServers").get(staticConf);
                    dnsServers.clear();
                    dnsServers.add(InetAddress.getByName(dns1));
//                    dnsServers.add(InetAddress.getByName(Constant.dns2)); // Google DNS as DNS2 for safety
                    // apply the new static configuration
                    wifiConfig.getClass().getMethod("setStaticIpConfiguration", staticConf.getClass()).invoke(wifiConfig, staticConf);
                }
                // apply the configuration change
                boolean result = wifiManager.updateNetwork(wifiConfig) != -1; //apply the setting
                Log.e("result",result+"");

                if (result) result = wifiManager.saveConfiguration(); //Save it

                Log.e("saveConfiguration",result+"");

                if (result) wifiManager.reassociate(); // reconnect with the new static IP

                Log.e("reassociate",result+"");


                int netId = wifiManager.addNetwork(wifiConfig);
                wifiManager.disableNetwork(netId);
                flag  = wifiManager.enableNetwork(netId, true);
                Log.e("netId",netId+"");


//                                            if(b){
//                                                Toast.makeText(getApplication(),"连接成功！",Toast.LENGTH_SHORT).show();
//                                            }else{
//                                                Toast.makeText(getApplication(),"连接失败！请确定服务器热点是否开启！",Toast.LENGTH_SHORT).show();
//
//                                            }
//                flag=true;


            } catch (Exception e) {
                e.printStackTrace();
                flag=false;
            }

        }
        return flag;
    }




    private static void setIpAssignment(String assign, WifiConfiguration wifiConf)
            throws SecurityException, IllegalArgumentException,
            NoSuchFieldException, IllegalAccessException {
        setEnumField(wifiConf, assign, "ipAssignment");
    }


    private static void setIpAddress(InetAddress addr, int prefixLength,
                                     WifiConfiguration wifiConf) throws SecurityException,
            IllegalArgumentException, NoSuchFieldException,
            IllegalAccessException, NoSuchMethodException,
            ClassNotFoundException, InstantiationException,
            InvocationTargetException {
        Object linkProperties = getField(wifiConf, "linkProperties");
        if (linkProperties == null)
            return;
        Class<?> laClass = Class.forName("android.net.LinkAddress");
        Constructor<?> laConstructor = laClass.getConstructor(new Class[]{

                InetAddress.class, int.class});
        Object linkAddress = laConstructor.newInstance(addr, prefixLength);
        ArrayList<Object> mLinkAddresses = (ArrayList<Object>) getDeclaredField(
                linkProperties, "mLinkAddresses");
        mLinkAddresses.clear();
        mLinkAddresses.add(linkAddress);
    }

    private static Object getField(Object obj, String name)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        Object out = f.get(obj);
        return out;
    }

    private static Object getDeclaredField(Object obj, String name)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getDeclaredField(name);
        f.setAccessible(true);
        Object out = f.get(obj);
        return out;
    }


    private static void setEnumField(Object obj, String value, String name)
            throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field f = obj.getClass().getField(name);
        f.set(obj, Enum.valueOf((Class<Enum>) f.getType(), value));
    }


    private static void setGateway(InetAddress gateway, WifiConfiguration wifiConf)
            throws SecurityException,
            IllegalArgumentException, NoSuchFieldException,
            IllegalAccessException, ClassNotFoundException,
            NoSuchMethodException, InstantiationException,
            InvocationTargetException {
        Object linkProperties = getField(wifiConf, "linkProperties");
        if (linkProperties == null)
            return;
        if (Build.VERSION.SDK_INT >= 14) { // android4.x版本
            Class<?> routeInfoClass = Class.forName("android.net.RouteInfo");
            Constructor<?> routeInfoConstructor = routeInfoClass
                    .getConstructor(new Class[]{InetAddress.class});
            Object routeInfo = routeInfoConstructor.newInstance(gateway);
            ArrayList<Object> mRoutes = (ArrayList<Object>) getDeclaredField(

                    linkProperties, "mRoutes");
            mRoutes.clear();
            mRoutes.add(routeInfo);
        } else { // android3.x版本
            ArrayList<InetAddress> mGateways = (ArrayList<InetAddress>) getDeclaredField(

                    linkProperties, "mGateways");
            //    mGateways.clear();
            mGateways.add(gateway);

        }
    }


    private static void setDNS(InetAddress dns, WifiConfiguration wifiConf)

            throws SecurityException, IllegalArgumentException,

            NoSuchFieldException, IllegalAccessException {

        Object linkProperties = getField(wifiConf, "linkProperties");
        if (linkProperties == null)
            return;
        ArrayList<InetAddress> mDnses = (ArrayList<InetAddress>)

                getDeclaredField(linkProperties, "mDnses");
        mDnses.clear(); // 清除原有DNS设置（如果只想增加，不想清除，词句可省略）
        mDnses.add(dns);
        //增加新的DNS
    }

    public static boolean isIP(String addr)
    {
        if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))
        {
            return false;
        }
        /**
         * 判断IP格式和范围
         */
        String rexp ="^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."+
        "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+
        "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+
        "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";


        Pattern pat = Pattern.compile(rexp);

        Matcher mat = pat.matcher(addr);

        boolean ipAddress = mat.find();

        return ipAddress;
    }
}